<template>
  <div class="config-station">
    <a-card :bordered="false">
      <div class="salesCard" id="table-wrapper">
        <a-tabs default-active-key="1" size="large" :tab-bar-style="{marginBottom: '0px', paddingLeft: '16px'}">
          <a-tab-pane loading="true" tab="表格" key="1">
            <div class="table-page-search-wrapper" style="margin-top: 35px">
              <a-form layout="inline">
                <a-row :gutter="0">
                  <a-col :md="6" :sm="24">
                    <a-form-item label="站点名称">
                      <a-input v-model="queryParam.stationName" allow-clear placeholder="请输入站点名称"/>
                    </a-form-item>
                  </a-col>
                  <a-col :md="10" :sm="24">
                  <span
                    class="table-page-search-submitButtons"
                    style="float: left;padding-left: 16px;">
                    <a-button type="primary" class="btn_search_reset" @click="$refs.table.refresh(true)"><a-icon
                      type="search"/>查询</a-button>
                    <a-button
                      style="margin-left: 8px"
                      class="btn_search_reset"
                      @click="() => {queryParam = {};$refs.table.refresh(true)}">
                      <a-icon
                        type="reload"/>重置</a-button>
                  </span>
                  </a-col>
                  <a-col :md="8" :sm="24">
                  <span
                    class="table-page-search-submitButtons"
                    style="float: right">
                    <a-button
                      class="btn_add"
                      type="primary"
                      @click="$refs.addForm.add(stationId)"
                      icon="plus">新增</a-button>
                  </span>
                  </a-col>
                </a-row>
              </a-form>
            </div>

            <s-table
              ref="table"
              size="middle"
              tableLayout="fixed"
              :columns="columns"
              :data="loadData"
              :alert="true"
              :rowKey="(record) => record.id"
              :row-selection="{ selectedRowKeys: selectedRowKeys,selectedRows:selectedRows,type: 'radio',onChange: onSelectChange }"
              :customRow="rowClick"
            >
            <span slot="action" slot-scope="text, record">
              <a @click="$refs.editForm.edit(record)" class="btn_edit">编辑</a>
              <a-divider type="vertical"/>
              <a-popconfirm class="btn_del" placement="topRight" title="确认删除？" @confirm="() => del(record)">
                <a>删除</a>
              </a-popconfirm>
            </span>
            </s-table>
            <add-form ref="addForm" @ok="handleOk"/>
            <add-form-map ref="addFormMap" @ok="handleOk"/>
            <edit-form ref="editForm" @ok="handleOk"/>
          </a-tab-pane>
          <a-tab-pane tab="地图" key="2" style="margin-top: 35px">
            <baidu-map
              ref="map"
              class="map"
              :center="map.center"
              :averageCenter="true"
              :scroll-wheel-zoom="true"
              :map-click="false"
              @ready="onReady"
              :zoom="map.zoom">
              <bm-context-menu>
                <bm-context-menu-item :callback="getLocation" text="添加"></bm-context-menu-item>
                <bm-navigation anchor="BMAP_ANCHOR_TOP_LEFT"></bm-navigation>
                <bm-geolocation
                  anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
                  :showAddressBar="true"
                  :autoLocation="true"></bm-geolocation>
                <bm-city-list anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-city-list>
                <bm-marker
                  v-for="marker of markers"
                  :key="marker.code"
                  :position="{lng: marker.stationLongitude, lat: marker.stationLatitude}"
                  @click="lookDetail(marker)"></bm-marker>
                <bm-info-window
                  :position="infoWindow"
                  :title="infoWindow.info.name"
                  :show="infoWindow.show"
                  @close="infoWindowClose"
                  @open="infoWindowOpen">
                  <p><span class="left">电站名：</span><span class="right">{{ infoWindow.info.name }}</span></p>
                  <p><span class="left">经度：</span><span class="right">{{ infoWindow.info.lng }}</span></p>
                  <p><span class="left">维度：</span><span class="right">{{ infoWindow.info.lat }}</span></p>
                  <p><span class="left">备注：</span><span class="right">{{ infoWindow.info.remark }}</span></p>
                </bm-info-window>
              </bm-context-menu>
            </baidu-map>
            <div class="search-wrap">
              <div class="search">
                <input class="search-input" type="text" v-model="keyword" placeholder="搜地点" @focus="handleFocus" @input="onSearch"  />
              </div>
              <!-- 检索结果 -->
              <div v-show="searchResult.length" class="search-result">
                <div v-for="(item, index) in searchResult" class="item" :key="index" @click="handleSelect(item)">
                  <p class="title">{{ item.title }}</p>
                </div>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>
  </div>
</template>

<script>
  import { STable } from '@/components'
  import { page, del, list } from '@/api/modular/main/bizstation/bizStationManage'
  import addForm from './station/addForm'
  import addFormMap from '../bizstation/addForm'
  import editForm from '../bizstation/editForm'
  import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
  import BmLocalSearch from 'vue-baidu-map/components/search/LocalSearch.vue'

  export default {
    components: {
      STable,
      addForm,
      addFormMap,
      editForm,
      BaiduMap,
      BmLocalSearch
    },

    props: {
      stationId: {
        type: Number,
        require: false
      }
    },

    data () {
      return {
        mapEl: null,
        BMap: null,
        keyword: '',
        searchResult: [],
        value: '',
        dataSource: [],
        advanced: false, // 高级搜索 展开/关闭
        queryParam: {}, // 查询参数
        columns: [ // 表头
          {
            title: '站点名称',
            dataIndex: 'stationName',
            width: 300,
            ellipsis: true
          },
          {
            title: '详细地址',
            dataIndex: 'stationAddress',
            width: 400,
            ellipsis: true
          },
          {
            title: '备注',
            dataIndex: 'stationRemark',
            ellipsis: true
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '180px',
            align: 'center',
            scopedSlots: { customRender: 'action' }
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return page(Object.assign(parameter, this.queryParam)).then((res) => {
            this.markers = res.data.rows
            return res.data
          })
        },
        selectedRowKeys: [],
        selectedRows: [],
        defaultExpandedKeys: [],
        replaceFields: {
          key: 'id'
        },
        map: {
          center: { lng: 117.233441, lat: 31.826578 }, // '合肥市',
          zoom: 7
        },
        points: [],
        markers: [],
        infoWindow: {
          lng: '',
          lat: '',
          show: false,
          info: {
            lat: '',
            lng: '',
            name: '',
            remark: ''
          }
        },
        // 查看详情
        lookDetail (data) {
          this.map.center = { lng: data.stationLongitude, lat: data.stationLatitude }
          this.map.zoom = 15
          this.infoWindow.show = true
          this.infoWindow.info.lng = data.stationLongitude
          this.infoWindow.lng = data.stationLongitude
          this.infoWindow.info.lat = data.stationLatitude
          this.infoWindow.lat = data.stationLatitude
          this.infoWindow.info.name = data.stationName
          this.infoWindow.info.remark = data.stationRemark
          // 为弹窗口标题添加title
          this.$nextTick(() => {
            var win = document.querySelector('.BMap_bubble_title')
            win.title = data.name
          })
        }
      }
    },

    created () {
      this.getAllStationList()
    },

    methods: {
      onReady({ BMap, map }) {
        this.BMap = BMap
        this.mapEl = map
      },
      handleFocus() {
        this.keyword = ''
      },
      onSearch(searchText) {
        const that = this
        function myFun(res) {
          var s = [];
          if (local.getStatus() == BMAP_STATUS_SUCCESS){
            for (var i = 0; i < res.getCurrentNumPois(); i ++) {
              s.push(res.getPoi(i));
            }
            that.searchResult = s
          } else{
            that.searchResult = s
          }
        }
        var options = {
          onSearchComplete: myFun
        }
        //
        var local = new BMap.LocalSearch(this.mapEl, options) //创建LocalSearch构造函数
        local.search(this.keyword) //调用search方法，根据检索词str发起检索
      },
      handleSelect(item) {
        for(let i=0; i<this.searchResult.length; i++) {
          if(item.uid === this.searchResult[i].uid){
            var bpoint = new Array()
            bpoint[1] = this.searchResult[i].point.lng
            bpoint[0] = this.searchResult[i].point.lat
            this.mapEl.clearOverlays() //清除地图上所有覆盖物
            this.mk = new BMap.Marker(this.searchResult[i].point) //根据所选坐标重新创建Marker
            this.mapEl.addOverlay(this.mk) //将覆盖物重新添加到地图中
            var pointLocation = new BMap.Point(bpoint[1], bpoint[0]);  //创建点坐标 当前位置
            this.mapEl.centerAndZoom(pointLocation, 10);
            // this.mapEl.panTo(this.searchResult[i].point) //将地图的中心点更改为选定坐标点
            this.keyword = item.title
            this.searchResult = []
          }
        }
      },
      rowClick: function (record) {
        return {
          on: {
            click: () => {
              this.selectedRowKeys = [record.id]
              this.selectedRows = [record]
              this.$refs.table.updateSelect(this.selectedRowKeys, this.selectedRows)
              // // this.$emit('ok', this.selectedRowKeys[0])
              this.$emit('ok', { stationId: this.selectedRowKeys[0], stationName: this.selectedRows[0].stationName })
            }
          }
        }
      },
      del (record) {
        del(record).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        }).catch((err) => {
          this.$message.error('删除错误：' + err.message)
        })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      getLocation (location) {
        const that = this
        /* 创建地址解析器的实例 */
        // eslint-disable-next-line no-undef
        const geoCoder = new BMap.Geocoder()
        /* 利用坐标获取地址的详细信息 */
        geoCoder.getLocation(location.point, res => {
          const address = res.address
          that.$refs.addFormMap.add(location.point, address)
          that.visible = false
        })
      },
      getAllStationList () {
        list().then(res => {
          if (res.success) {
            this.markers = res.markers
            if (this.stationId !== 0) {
              this.selectedRowKeys = [this.stationId]
              this.$refs.table.updateSelect(this.selectedRowKeys, this.selectedRows)
            }
          }
        })
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRows = selectedRows
        this.selectedRowKeys = selectedRowKeys
        this.$emit('ok', { stationId: selectedRowKeys[0], stationName: selectedRows[0].stationName })
      },
      infoWindowClose (e) {
        this.infoWindow.show = false
      },
      infoWindowOpen (e) {
        this.infoWindow.show = true
      }
    }
  }
</script>
<style lang="less" scoped>
  @import '../~@/assets/css/list.less';

  .ant-card .ant-card-body .table-wrapper .ant-table-wrapper .ant-table-default,
  .ant-card .ant-card-body .table-wrapper .ant-table-wrapper .ant-table-middle{
    //height: 580px;
    height: 30vh !important;
    border: 10px solid transparent;
    // border-image: url('../assets/img/border_table.png') 18 round;
    border-image-width: 13px;
  }

  .table-operator {
    margin-bottom: 18px;
  }

  button {
    margin-right: 8px;
  }

  .map {
    width: 100%;
    height: 60vh;
    touch-action: none;
  }

  .anchorBL {
    display: none;
  }

  .BMap_cpyCtrl {
    display: none;
  }
  .ant-card .ant-card-body .table-wrapper .ant-table-wrapper .ant-table-default {
    //height: 580px;
    height: 50vh !important;
  }
  .search-wrap{
    position: absolute;
    top: 120px;
    left: 0;
    width: 428px;
    box-sizing: border-box;
    padding: 0 64px;
    .search{
      background-color: #fff;
      padding: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .search-input{
        flex: 1;
        outline: none;
        border: none;
        width: 100%;
        height: 100%;
      }
      .search-btn{
        font-size: 28px;
      }
    }
    .search-result{
      min-height: 96px;
      max-height: 320px;
      overflow: hidden;
      overflow-y: auto;
      background-color: #fff;
      padding: 0 12px;
      border-top: 1px solid #ebeef2;
      .item{
        line-height: 32px;
        text-align: left;
        cursor: pointer;
      }
    }
  }
</style>
